<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="发帖" name="first">
        <el-form
          :model="postForm"
          :rules="postRules"
          ref="postForm"
          label-width="100px"
        >
          <el-form-item label="标题：" prop="titleName">
            <el-row>
              <el-col :span="10">
                <el-input v-model="postForm.titleName"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="推荐网站：" prop="jiedian">
            <el-switch
              v-model="postForm.isLink"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchBtn"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="内容：" prop="pDescribe">
            <froalaEditor
              :label="editorContentLabel"
              v-model="postForm.pDescribe"
            ></froalaEditor>
          </el-form-item>
          <el-form-item label="封面："  prop="pImg" label-width="120px">
          <el-upload
              class="upload-demo"
              action="http://localhost:3000/express/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="handleAvatarSuccess"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

            <!-- :src="postForm.pImgFile" -->
          <!-- <el-image v-if="postForm.pImgFile!=null"
            :src="postForm.pImgFile"
            v-model="postForm.pImgFile"
          ></el-image> -->
        </el-form-item>
          <el-form-item label="标签：" prop="tId">
            <el-select v-model="postForm.tId" placeholder="请选择标签">
              <el-option
                v-for="item in tags"
                :key="item.tId"
                :label="item.tName"
                :value="item.tId"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 条件渲染 根据isEdit显示发布或者修改 -->
          <el-form-item v-if="!isEdit">
            <el-button type="primary" @click="onSubmit(1, postForm)"
              >发布</el-button
            >
            <el-button @click="onSubmit(-1, postForm)">存入草稿</el-button>
          </el-form-item>
          <el-form-item v-else>
            <el-button type="primary" @click="editArticle">修改</el-button>
          </el-form-item>
        </el-form>
        <el-dialog
          title="节点"
          :visible="centerDialogVisible"
          :show-close="false"
          width="30%"
          center
        >
          <el-form
            ref="wikiForm"
            :model="wikiForm"
            :rules="wikiRules"
            label-width="80px"
          >
            <el-form-item label="名称" prop="wName">
              <el-input v-model="wikiForm.wName"></el-input>
            </el-form-item>
            <el-form-item label="领域" prop="eId">
              <el-radio-group v-model="wikiForm.eId">
                <el-radio
                  v-for="eItem in edition"
                  :key="eItem.eId"
                  :label="eItem.eId"
                >{{eItem.eName}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="链接" prop="wLink">
              <el-input v-model="wikiForm.wLink"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submitDialog(wikiForm)"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-tab-pane>
      <!-- <el-tab-pane label="草稿管理" name="second">2</el-tab-pane> -->
    </el-tabs>
  </div>
</template>
<script>
import froalaEditor from './froala-editor.vue'
export default {
  inject:['reload'],//注入依赖
  components: { froalaEditor },
  data () {
    return {
      fileList:[],
      tags: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      editorContentLabel: '',
      isEdit: false,
      channels: [],
      activeName: 'first',
      wikiForm: {
        wName: '',
        wLink: '',
        eId: 1
      },
      wikiRules: {
        wName: [
          { required: true, message: '请输入节点名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        wLink: [{ required: true, message: '请输入链接', trigger: 'blur' }],
        eId: [{ required: true, message: '请选择领域', trigger: 'change' }]
      },
      centerDialogVisible: false,
      postForm: {
        isLink: false,
        titleName: '',
        pImg: "",
        pDescribe: '',
        pTime: "",
        tId: 1
      },
      edition: [],
      // 验证规则
      postRules: {
        titleName: [
          { required: true, message: '请输入帖子标题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在 5 到 30 个字符', trigger: 'blur' }
        ],
        pDescribe: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        tId: [{ required: true, message: '请选择标签', trigger: 'blur' }]
      },
      userInfo:{}
    }
  },
  mounted(){

  },
  created () {
    this.$bus.$on("postMes",(msg)=>{
      console.log(msg)
      this.postForm = msg
      console.log(this.postForm)
    })
    this.getTagsList()
    this.getEdition()
    this.getInfo();
  },
  methods: {
    // 推荐网站 提交按钮
    submitDialog (wikiForm) {
      console.log(wikiForm)
      this.$refs.wikiForm.validate(valid => {
        if (valid) {
          this.centerDialogVisible = false
        } else {
          this.$message({
            message: '请检查必填内容是否填写哦',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 推荐链接 开关
    switchBtn () {
      console.log(this.postForm.isLink)
      console.log(this.centerDialogVisible)
      this.centerDialogVisible = this.postForm.isLink
    },
    // 关闭节点弹窗
    closeDialog () {
      this.centerDialogVisible = false
      this.postForm.isLink = false
      this.wikiForm = {}
    },
    // 获取领域
    getEdition () {
      this.$axios.getAllEdition().then(res => {
        console.log(res)
        this.edition = res.data
      })
    },
    // 获取标签
    getTagsList () {
      this.$axios.getTagsList().then(res => {
        console.log(res)
        this.tags = res.data
      })
    },
    // onUploadChange (file) {
    //   //获取文件
    //   this.postForm.pImgFile = file
    //   this.$refs.postForm.validateField("pImgFile");
    // },
    // 头部点击事件，切换不同功能
    handleClick (tab, event) {
      console.log(tab, event)
    },
    // 修改帖子
    editArticle () {
      console.log('修改')
    },
    getInfo(){
       const params = {}
      // console.log(this.cookies.getToken('X-Token'))
      if (this.cookies.getToken('X-Token') != undefined) {
        params.token = this.cookies.getToken('X-Token')
        this.$axios.getUserInfo(params).then(res => {
          // console.log(res)
          this.userInfo = res.data
        })
      } else {
        this.$router.push('/')
      }
    },
    // 发布帖子
    onSubmit (status, postForm) {
      // status表示是否上传帖子，还是存为草稿
      // status 0     1       2     3     4
      //       草稿 全部帖子 进行中 通过 未通过
      console.log(status)
      this.postForm.isUpload = status
      this.postForm.uId = this.userInfo.uId
      var params = {}
      this.postForm.pTime =  this.common.formateDate(new Date(),'yyyy-MM-dd hh:mm:ss')
      params.postForm = this.postForm
      if(this.postForm.isLink){
        params.wikiForm = this.wikiForm
      }
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // 提交
          this.$axios.postMes(params).then(res=>{
            // console.log(res)
            if(res.code==20000){
              this.$message({
                message: res.message,
                type: 'success'
              });
              // this.$router.push("/submit/article")
              this.reload()
            }else{
              this.$message.error(res.message);
            }
          })
        } else {
          this.$message({
            message: '请检查必填内容是否填写哦',
            type: 'warning'
          })
          return false
        }
      })
      console.log(this.postForm)
      console.log(this.wikiForm)
    },
     handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      window.open(file.response.url)
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleAvatarSuccess(res, file) {
      // this.editForm.img = res.url
      console.log(res)
      console.log(file)
      this.postForm.pImg = res.url
    }
  }
}
</script>
<style scoped>
.el-form-item {
  padding-right: 50px;
  margin-bottom: 20px;
}
</style>
